<template>
  <div class="login-container">
    <el-form :model="form" :rules="rules" ref="form" class="login-form">
      <h2 class="title">中医馆管理系统</h2>
      <el-form-item prop="username">
        <el-input v-model="form.username" placeholder="用户名"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="form.password" type="password" placeholder="密码"></el-input>
      </el-form-item>
      <el-button type="primary" @click="handleLogin" :loading="loading">登录</el-button>
    </el-form>
  </div>
</template>

<script>
import { login } from '@/api/user'

export default {
  data() {
    return {
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      loading: false
    }
  },
  methods: {
    handleLogin() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          login(this.form).then(response => {
            this.$store.commit('SET_TOKEN', response.data.token)
            // 使用replace而不是push避免导航循环
            this.$router.replace('/dashboard') 
          }).finally(() => {
            this.loading = false
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #2d3a4b;
}
.login-form {
  width: 400px;
  padding: 30px;
  background: #fff;
  border-radius: 6px;
}
.title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}
</style>